#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(ui->connectButton,SIGNAL(clicked()),this,SLOT(send()));
    initSockSingnals(&systemSock);
    initSockSingnals(&commandSock);
    initSockSingnals(&videoSock);
    initSockSingnals(&audioSock);
    connectAll();
}

MainWindow::~MainWindow()
{
    disconnectAll();
    delete ui;
}

void MainWindow::initSockSingnals(QTcpSocket *sock)
{
    connect(sock,SIGNAL(connected()),this,SLOT(connected()));
    connect(sock,SIGNAL(disconnected()),this,SLOT(disconnected()));
    connect(sock,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(error(QAbstractSocket::SocketError)));
    connect(sock,SIGNAL(readyRead()),this,SLOT(read()));
}

void MainWindow::connectAll()
{
    systemSock.connectToHost("127.0.0.1",6669);
    commandSock.connectToHost("127.0.0.1",6669);
    videoSock.connectToHost("127.0.0.1",6669);
    audioSock.connectToHost("127.0.0.1",6669);
}

void MainWindow::disconnectAll()
{
    if(systemSock.isOpen())systemSock.close();
    if(commandSock.isOpen())commandSock.close();
    if(videoSock.isOpen())videoSock.close();
    if(audioSock.isOpen())audioSock.close();
}

void MainWindow::connected()
{
    ui->logEdit->insertPlainText("<>: connected to host\n");
}

void MainWindow::disconnected()
{
    ui->logEdit->insertPlainText("<>: disconnected from host\n");
}

void MainWindow::error(QAbstractSocket::SocketError error)
{
    QTcpSocket *sock = (QTcpSocket *)sender();
    ui->logEdit->insertPlainText("<>: "+sock->errorString()+"\n");
}

void MainWindow::send()
{
    systemSock.write(ui->commandLine->text().toAscii());
    ui->logEdit->insertPlainText("<< "+ui->commandLine->text()+"\n");
}

void MainWindow::read()
{
    QTcpSocket *sock = (QTcpSocket *)sender();
    while(sock->canReadLine())
    {

        ui->logEdit->insertPlainText(">> "+sock->readLine());
    }
}

void MainWindow::initNetwork()
{
/*
    const bool canStartIAP = (manager.capabilities()& QNetworkConfigurationManager::CanStartAndStopInterfaces);
    QNetworkConfiguration cfg = manager.defaultConfiguration();
    if (!cfg.isValid() || (!canStartIAP && cfg.state() != QNetworkConfiguration::Active)) {
        ui->logEdit->insertPlainText("<>: No Access Point found\n");
        return;
    }
    session = new QNetworkSession(cfg, this);
    session->open();
    session->waitForOpened(-1);*/
}
